﻿/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        set<ListNode*> s;
        ListNode* cur = head;
        while (cur)//为环在循环中返回入环节点
        {
            if (s.count(cur))//如果count不为0，说明之前已经存放过该节点地址，就是入环节点
                return cur;
            else
                s.insert(cur);
            cur = cur->next;
        }
        //不为环则直接返回null
        return nullptr;
    }
};